#include "taiyun.h"

Taiyun::Taiyun(AnatomicalLink *link, double maxCorr, double minCorr, QWidget *parent)
    : QWidget(parent)
{
	im = NULL;
    aLink = link;
	cMax = maxCorr;
	cMin = minCorr;
	recreate();
}

Taiyun::~Taiyun()
{
	if(im)
		im->~QImage();  //destroy
}

void Taiyun::recreate()
{
	if(im)
		im->~QImage();  //destroy
	im = new QImage(width(),height(),QImage::Format_ARGB32_Premultiplied);

	double correlation = aLink->correlation();
	double distance = aLink->distance();

	double predictedCorrelation = 1.0;
	if(distance != 0)
        predictedCorrelation = 1.0/(distance*distance);
	
	QPainter painter(im);
    QBrush brush;
    brush.setStyle(Qt::SolidPattern);

    QPen pen;
    pen.setStyle(Qt::SolidLine);
    pen.setColor(Qt::black);
	
	double rgb[3] = {0, 0, 0};
	ColorMap::getInstance()->getLookupTable()->GetColor(correlation,rgb);
	brush.setColor(QColor::fromRgb(rgb[0]*255,rgb[1]*255,rgb[2]*255));
    
	painter.setBrush(brush);
    painter.setPen(pen);

	int size;
	//int scalar_w = ((QTableWidget*)this->parentWidget())->columnWidth(1);
	//int scalar_h = ((QTableWidget*)this->parentWidget())->rowHeight(1);
	int magic_scalar = 100;

	if(correlation<0)
		size = abs((correlation / cMin) * magic_scalar);
	else
		size = abs((correlation / cMax) * magic_scalar);
	
	//size /= std::max(scalar_w,scalar_h);
	
	//painter.drawEllipse(QRectF(-(abs(correlation/predictedCorrelation)*5) / 2.0, -(abs(correlation/predictedCorrelation)*5) / 2.0, (abs(correlation/predictedCorrelation)*5), (abs(correlation/predictedCorrelation)*5)));
	painter.drawEllipse(QPoint(width()/2,height()/2),size,size);
}

double Taiyun::GetCorrelation()
{
	return aLink->correlation();
}

AnatomicalLink* Taiyun::getLink()
{
    return aLink;
}

void Taiyun::paintEvent(QPaintEvent *)
{
	double distance = aLink->distance();
	double correlation = aLink->correlation();

	QPainter painter(this);
    
	/*painter.translate(width() / 2, height() / 2);

    QBrush brush;
    brush.setStyle(Qt::SolidPattern);

    QPen pen;
    pen.setStyle(Qt::SolidLine);
    pen.setColor(Qt::black);

	brush.setColor(QColor::fromRgb(ColorMap()->GetRedValue(correlation),ColorMap()->GetGreenValue(correlation),ColorMap()->GetBlueValue(correlation)));
    
	painter.setBrush(brush);
    painter.setPen(pen);

    double predictedCorrelation = 1.0;
    
	if(distance != 0)
        predictedCorrelation = 1.0/(distance*distance);

    double debug = correlation/predictedCorrelation;

	painter.drawEllipse(QRectF(-(abs(correlation/predictedCorrelation)*10) / 2.0, -(abs(correlation/predictedCorrelation)*10) / 2.0, (abs(correlation/predictedCorrelation)*10), (abs(correlation/predictedCorrelation)*10)));
	*/
	painter.drawImage(QRectF(0,0,std::min(width(),height()),std::min(width(),height())),*im);
}
